import pyautogui
import cv2
import os
import time
import numpy as np

#灰度匹配
def find_image_on_screen(image_path):
    # 截取屏幕图片
    pyautogui.screenshot(imageFilename="screen.bmp")

    # 读取屏幕截图和目标图片
    screenpic = cv2.imread("screen.bmp")
    mypic = cv2.imread(image_path)

    # 初始化SIFT特征检测器
    sift = cv2.SIFT_create()

    # 检测和计算图片的关键点和描述符
    screenPicKP, screenPicDES = sift.detectAndCompute(screenpic, None)
    myPicKP, myPicDES = sift.detectAndCompute(mypic, None)

    # 设置FLANN匹配参数
    trees = 100
    checks = 1000
    indexParams = dict(algorithm=0, trees=int(trees))
    searchParams = dict(checks=int(checks))

    # 创建FLANN匹配器
    flann = cv2.FlannBasedMatcher(indexParams, searchParams)

    # 进行特征匹配
    matches = flann.knnMatch(screenPicDES, myPicDES, k=2)

    # 按距离排序
    matches = sorted(matches, key=lambda x: x[0].distance)

    # 寻找最佳匹配的位置
    x, y = None, None
    max_init_num = 0.4
    init_num = 0.1
    while init_num <= max_init_num:
        goodMatches = [m for m, n in matches if m.distance < init_num * n.distance]
        if goodMatches:
            index = int(len(goodMatches) / 2)
            try:
                x, y = screenPicKP[goodMatches[index].queryIdx].pt
                break
            except IndexError:
                pass
        init_num += 0.1

    # 清理临时文件
    os.remove("screen.bmp")

    # 返回结果
    return x, y

# 此函数封装循环找图，并将鼠标移向目标位置,参数：图片路径，超时时间
def remove_mouse(image_path,timeout):
    start_time = time.time()
    try:
        while True:
            x, y = find_image_on_screen(image_path)
            if x is not None and y is not None:
                break

            # 检查是否超时
            if time.time() - start_time > timeout:
                return

            # 等待一段时间后再次尝试
            time.sleep(1)

            # 移动鼠标到指定位置
        pyautogui.moveTo(x, y)

        pyautogui.click()

    except Exception as e:
        print(f"发生错误：{e}")

# 颜色匹配
def find_colorimage(image_path, timeout, click_mode=True):
    start_time = time.time()
    found = False  # 添加一个变量来跟踪是否找到了图像
    while True:
        # 截屏
        screenshot = pyautogui.screenshot()
        screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

        # 读取目标图像
        template = cv2.imread(image_path)
        w, h = template.shape[:-1][::-1]

        # 模板匹配
        res = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
        threshold = 0.8  # 可以根据需要调整阈值
        loc = np.where(res >= threshold)

        # 如果找到匹配
        if len(loc[0]) > 0:
            for pt in zip(*loc[::-1]):
                # 移动鼠标到匹配位置

                if click_mode:  # 根据click_mode决定是否点击
                    pyautogui.moveTo(pt[0] + w // 2, pt[1] + h // 2)
                    pyautogui.click()

                found = True  # 标记找到了图像
                return found  # 返回找到图像的结果

        # 检查是否超时
        if (time.time() - start_time) > timeout:
            break

    return found

#灰度判断
def find_dark(image_path):
    x,y=find_image_on_screen(image_path)
    if x is not None and y is not None:
        return True
    else:
        return False


